package demo.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.richstonedt.garnet.model.bo.UserAuthenticationBO;
import com.richstonedt.garnet.springboot.starter.utils.JwtTokenUtils;
import demo.entity.SystemUser;
import demo.service.GarnetUserService;
import demo.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * Garnet服务类实现类
 * </p>
 *
 * @author
 * @since 2021-04-01
 */
@Service
public class GarnetUserServiceImpl implements GarnetUserService {

    @Resource
    private JwtTokenUtils jwtTokenUtils;

    @Autowired
    private RedisService redisService;

    @Override
    public UserAuthenticationBO getCurrentUser(HttpServletRequest request) {
        if (ObjectUtil.isNull(request)) {
            return null;
        }
        String token = jwtTokenUtils.getToken(request);
        if (StrUtil.isEmpty(token)) {
            return null;
        }
        String[] userToken = jwtTokenUtils.parseToken(token);
        if (null == userToken) {
            return null;
        }
        UserAuthenticationBO userAuthenticationBO = (UserAuthenticationBO) jwtTokenUtils.loadUserByToken(userToken);
        return userAuthenticationBO;
    }

    @Override
    public String getToken(HttpServletRequest request) {
        return jwtTokenUtils.getToken(request);
    }

    @Override
    public SystemUser getLoginUser(HttpServletRequest request) {

        String username = this.getCurrentUser(request).getUsername();

        SystemUser loginUser = redisService.getObject("rziomp" + username);

        return loginUser;
    }

}
